"""
日志模块
"""

import logging
import sys
from pathlib import Path
from logging.handlers import RotatingFileHandler
from typing import Optional

from .config import Config


_loggers = {}


def setup_logger(
    name: str = "SAMTool",
    config: Optional[Config] = None
) -> logging.Logger:
    """
    设置日志记录器
    
    Args:
        name: 日志记录器名称
        config: 配置对象
    
    Returns:
        logging.Logger: 日志记录器
    """
    # 如果已经设置过，直接返回
    if name in _loggers:
        return _loggers[name]
    
    if config is None:
        config = Config()
    
    # 创建日志记录器
    logger = logging.getLogger(name)
    
    # 设置日志级别
    log_level = config.get('logging.level', 'INFO')
    logger.setLevel(getattr(logging, log_level))
    
    # 避免重复添加处理器
    if logger.handlers:
        return logger
    
    # 日志格式
    log_format = config.get(
        'logging.format',
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    formatter = logging.Formatter(log_format)
    
    # 控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.DEBUG)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    
    # 文件处理器
    log_file = config.get('logging.file', 'logs/app.log')
    log_file_path = Path(log_file)
    
    # 确保日志目录存在
    log_file_path.parent.mkdir(parents=True, exist_ok=True)
    
    max_bytes = config.get('logging.max_bytes', 10485760)  # 10MB
    backup_count = config.get('logging.backup_count', 5)
    
    file_handler = RotatingFileHandler(
        log_file_path,
        maxBytes=max_bytes,
        backupCount=backup_count,
        encoding='utf-8'
    )
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    
    # 缓存日志记录器
    _loggers[name] = logger
    
    logger.info(f"日志系统已初始化 [级别: {log_level}, 文件: {log_file}]")
    
    return logger


def get_logger(name: str = "SAMTool") -> logging.Logger:
    """
    获取日志记录器
    
    Args:
        name: 日志记录器名称
    
    Returns:
        logging.Logger: 日志记录器
    """
    if name in _loggers:
        return _loggers[name]
    return setup_logger(name)

